package com.amigo;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amigo.helper.Constants;
import com.amigo.helper.ImageLoader;
import com.amigo.helper.JsonFileUtility;
import com.amigo.helper.ServiceHandler;
import com.amigo.views.CirclePageIndicator;

public class Profile extends Activity {

	String Name = "No Name";
	String Location="No Location Specified";
	String Dob , About , Interests;
	TextView Profile_name , Name_tv , Dob_tv , Location_tv , About_tv , Interests_tv  ;
	List<Bitmap> list_images;
	private MyPagerAdapter adapter;
	private ViewPager pager;
	private Boolean Success_add = false;
	private String SearchResult , Result_user , Message_add , DB_UserToken; 
	int index_profile ;
	private int ID , Credits;
	
	private String url_addfriend = Constants.base_url + "sendFriendRequest";
	private String url_deletefriend = Constants.base_url + "ignoreUser";
	private String url_deduct_credits = Constants.base_url + "updateCredits";
	
	
	CirclePageIndicator mIndicator;
	
	public ImageLoader imageLoader;
	
	ProgressDialog ringProgressDialog =null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_profile);
		DB_UserToken = JsonFileUtility.ReadJsonData(Constants.TAG_UserGUID);
		
		Intent i = getIntent() ;
		index_profile = i.getIntExtra("Index", -1);
		
	
		list_images = new ArrayList<Bitmap>();
		
		
		imageLoader=new ImageLoader(getApplicationContext());
		
		Profile_name = (TextView) findViewById(R.id.name_profile);
		
		About_tv = (TextView) findViewById(R.id.about_profile);
		About_tv.setMovementMethod(ScrollingMovementMethod.getInstance());
		
		Interests_tv =(TextView) findViewById(R.id.interests_profile);
		
		Name_tv = (TextView) findViewById(R.id.name_profile2);
		
		
		Dob_tv = (TextView) findViewById(R.id.dob_profile);
		
		Location_tv = (TextView) findViewById(R.id.location_profile);
		
		 mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
		
		pager = (ViewPager) findViewById(R.id.pager_profile);
		
		adapter = new MyPagerAdapter();

		 ringProgressDialog = new ProgressDialog(this);
		 ringProgressDialog.setIndeterminate(true);
		 ringProgressDialog.setCancelable(false);
		 ringProgressDialog.setTitle("Please Wait");
			ringProgressDialog.setMessage("Getting Profile Information");
			
			if (i.hasExtra("user_from_amigos"))
			{
				Result_user = i.getStringExtra("user_from_amigos");
				new ProfileDataLoaderFromObject().execute();
			}
			else if (i.hasExtra("user_from_pendingrequets"))
			{
				Result_user = i.getStringExtra("user_from_pendingrequets");
				new ProfileDataLoaderFromObject().execute();
			}
			else
			{
			SearchResult = JsonFileUtility.ReadJsonData(Constants.TAG_SearchResults);
			new ProfileDataLoader().execute();
			}
		
		
	}
	
	public void sendreq(View view)
	{
	
		Log.d("id of the user " , "" + ID);
		new AddFriendTask().execute();
	}
	
	
	
	public void delreq(View view)
	{
		
		Log.d("id of the user " , "" + ID);
		new DeleteFriendTask().execute();
		
	}
	
	

	public void prev(View v){
		
		Intent in = getIntent() ;
		
		if (in.hasExtra("user_from_amigos"))
		{
			Intent i = new Intent (Profile.this , Amigos.class);
			startActivity(i);
			finish();
		}
		else if (in.hasExtra("user_from_pendingrequets"))
		{
			Intent i = new Intent (Profile.this , Notifications.class);
			startActivity(i);
			finish();
		}
		else
		{
			Intent i = new Intent (Profile.this , Dashboard.class);
			startActivity(i);
			finish();
		}
	
	}
	
	private class MyPagerAdapter extends PagerAdapter {

	 		@Override
	 		public int getCount() {
	 			return list_images.size();
	 		}

	 		/**
	 		 * Create the page for the given position. The adapter is responsible
	 		 * for adding the view to the container given here, although it only
	 		 * must ensure this is done by the time it returns from
	 		 * {@link #finishUpdate()}.
	 		 * 
	 		 * @param container
	 		 *            The containing View in which the page will be shown.
	 		 * @param position
	 		 *            The page position to be instantiated.
	 		 * @return Returns an Object representing the new page. This does not
	 		 *         need to be a View, but can be some other container of the
	 		 *         page.
	 		 */
	 		@Override
	 		public Object instantiateItem(View collection, int position) {
	 			ImageView view = new ImageView(Profile.this);
	 			view.setImageBitmap(list_images.get(position));
	 			
	 			((ViewPager) collection).addView(view, 0);

	 			return view;
	 		}

	 		@Override
			public boolean isViewFromObject(View view, Object object) {
				return view == ((ImageView) object);
			}

			/**
	 		 * Remove a page for the given position. The adapter is responsible for
	 		 * removing the view from its container, although it only must ensure
	 		 * this is done by the time it returns from {@link #finishUpdate()}.
	 		 * 
	 		 * @param container
	 		 *            The containing View from which the page will be removed.
	 		 * @param position
	 		 *            The page position to be removed.
	 		 * @param object
	 		 *            The same object that was returned by
	 		 *            {@link #instantiateItem(View, int)}.
	 		 */
	 		@Override
	 		public void destroyItem(View collection, int position, Object view) {
	 			((ViewPager) collection).removeView((ImageView) view);
	 		}

	 		/**
	 		 * Called when the a change in the shown pages has been completed. At
	 		 * this point you must ensure that all of the pages have actually been
	 		 * added or removed from the container as appropriate.
	 		 * 
	 		 * @param container
	 		 *            The containing View which is displaying this adapter's
	 		 *            page views.
	 		 */
	 		@Override
	 		public void finishUpdate(View arg0) {
	 		}

	 		@Override
	 		public void restoreState(Parcelable arg0, ClassLoader arg1) {
	 		}

	 		@Override
	 		public Parcelable saveState() {
	 			return null;
	 		}

	 		@Override
	 		public void startUpdate(View arg0) {
	 		}
	 		
	 	}
	
	public class ProfileDataLoader extends AsyncTask<Void, Void, Void> {
		JSONObject jsonObj ; 

		@Override
		protected void onPreExecute() {
			
			
			ringProgressDialog.show();
			super.onPreExecute();
			
			
		}
		
		
		@Override
		protected Void doInBackground(Void... params) {
			
			
			try {
				JSONArray jsonarray = new JSONArray(SearchResult);
				 jsonObj = jsonarray.getJSONObject(index_profile);
				 Name = jsonObj.getString("name");
				Location = jsonObj.getString("location");
				Dob = jsonObj.getString("dob");
				About = jsonObj.getString("about");
				Interests = jsonObj.getString("interests");
				String id_temp = jsonObj.getString("id");
				ID = Integer.parseInt(id_temp);
				Log.d("id at task", "" + ID);

				if (jsonObj.opt("profile_images") instanceof Boolean  )
				{
					Bitmap temp_bmp = BitmapFactory.decodeResource(getResources(), R.drawable.default_dp_face);
					list_images.add(temp_bmp);
					
				
				}
				else{
					
					JSONArray profile_images_array = jsonObj.getJSONArray("profile_images");
					for (int index=0 ; index < profile_images_array.length(); index++)
					{
					JSONObject profile_image_object = profile_images_array.getJSONObject(index);
					String temp_url = profile_image_object.getString("image_url");
					Bitmap temp_bmp = imageLoader.getBitmap(Constants.base_url + temp_url);
					list_images.add(temp_bmp);
					}
					}
				
			} catch (JSONException e) {
				
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			
			super.onPostExecute(result);
			
			
			adapter.notifyDataSetChanged();
			Profile_name.setText(Name);
			Dob_tv.setText(Dob);
			Name_tv.setText(Name);
			Location_tv.setText(Location);
		//	About = About.replaceAll("\\", "");
			About_tv.setText(About);
			Interests_tv.setText(Interests);
			
			pager.refreshDrawableState();
			
			pager.setAdapter(adapter);
			
	        mIndicator.setViewPager(pager);
	        ringProgressDialog.dismiss();
		}
	}
	
	
	public class ProfileDataLoaderFromObject extends AsyncTask<Void, Void, Void> {
		JSONObject jsonObj ; 

		@Override
		protected void onPreExecute() {
			
			
			ringProgressDialog.show();
			super.onPreExecute();
			
			
		}
		
		
		@Override
		protected Void doInBackground(Void... params) {
			
			
			try {
				
				 jsonObj = new JSONObject(Result_user);
				 Name = jsonObj.getString("name");
				Location = jsonObj.getString("location");
				Dob = jsonObj.getString("dob");
				About = jsonObj.getString("about");
				Interests = jsonObj.getString("interests");
				String id_temp = jsonObj.getString("id");
				ID = Integer.parseInt(id_temp);

				if (jsonObj.opt("profile_images") instanceof Boolean  )
				{
					Bitmap temp_bmp = BitmapFactory.decodeResource(getResources(), R.drawable.default_dp_face);
					list_images.add(temp_bmp);
					
				
				}
				else{
					
					JSONArray profile_images_array = jsonObj.getJSONArray("profile_images");
					for (int index=0 ; index < profile_images_array.length(); index++)
					{
					JSONObject profile_image_object = profile_images_array.getJSONObject(index);
					String temp_url = profile_image_object.getString("image_url");
					Bitmap temp_bmp = imageLoader.getBitmap(Constants.base_url + temp_url);
					list_images.add(temp_bmp);
					}
					}
				
			} catch (JSONException e) {
				
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			
			super.onPostExecute(result);
			
			
			adapter.notifyDataSetChanged();
			Profile_name.setText(Name);
			Dob_tv.setText(Dob);
			Name_tv.setText(Name);
			Location_tv.setText(Location);
			About_tv.setText(About);
			Interests_tv.setText(Interests);
			
			pager.refreshDrawableState();
			
			pager.setAdapter(adapter);
			
	        mIndicator.setViewPager(pager);
	        ringProgressDialog.dismiss();
		}
	}
	
	
	private class AddFriendTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			Credits = Integer.parseInt(JsonFileUtility
					.ReadJsonData(Constants.Tag_Credits));
			Log.d("Credits", "" + Credits);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			Success_add = false ; 
			if (Credits > 0) {
				ServiceHandler sh = new ServiceHandler();
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("requestedBy", DB_UserToken));
				params.add(new BasicNameValuePair("requestedTo", "" + ID));

				// Making a request to url and getting response
				String jsonStr = sh.makeServiceCall(url_addfriend,
						ServiceHandler.POST, params);
				Log.d("Response: ", "> " + jsonStr);
				if (jsonStr != null) {
					JSONObject jsonobj;
					try {
						jsonobj = new JSONObject(jsonStr);
						Success_add = jsonobj.getBoolean("success");
						Message_add = jsonobj.getString("message");

					} catch (JSONException e) {
						
						e.printStackTrace();
					}

				}
			}
			else
			{
				Log.d("credits " , "you dont have enough credits");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
if (Credits > 0 )
{
			if (Success_add == true) {
				new DeductCredits().execute();
				
				Toast.makeText(getApplicationContext(), Message_add,
						Toast.LENGTH_SHORT).show();

				JsonFileUtility.CreateAndSaveFile(Constants.Tag_Credits, ""
						+ Credits);

			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						Profile.this);
				builder.setTitle("Add Amigo ");
				builder.setMessage(Message_add);
				builder.setNeutralButton("Ok",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						});

				AlertDialog alertDialog = builder.create();
				alertDialog.setCancelable(false);

				// show it
				alertDialog.show();
			}
		}
else
{
	AlertDialog.Builder builder = new AlertDialog.Builder(
			Profile.this);
	builder.setTitle("Oops ! Looks like you have run out of credits");
	builder.setMessage("You Do Not Have Enough Credits ! \nYou can Buy More Credits in the My Account Section");
	builder.setPositiveButton("Buy More Credits",
			new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog,
						int which) {
					
					//TODO - GOTO My accounts sections and buy credits

				}
			});
	
	builder.setNegativeButton("Cancel",
			new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog,
						int which) {
					
					

				}
			});
	

	AlertDialog alertDialog = builder.create();
	alertDialog.setCancelable(false);

	// show it
	alertDialog.show();}
	}

	}
	private class DeductCredits extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			Credits = Credits - 1;
			Log.d("Credits on pre execute", "" + Credits);
			

		}

		@Override
		protected Void doInBackground(Void... params) {
			Log.d("do in background", "started");
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("id", DB_UserToken));
			param.add(new BasicNameValuePair("credits", "" + Credits));

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url_deduct_credits,
					ServiceHandler.POST, param);
			Log.d("RESPONSE", jsonStr);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			JsonFileUtility.CreateAndSaveFile(Constants.Tag_Credits, ""
					+ Credits);
			prev(null);
		}

	}

	private class DeleteFriendTask extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected Void doInBackground(Void... arg) {
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("who", DB_UserToken));
			params.add(new BasicNameValuePair("whom", "" + ID));

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url_deletefriend,
					ServiceHandler.POST, params);
			Log.d("Response: ", "> " + jsonStr);
			if (jsonStr != null) {
				JSONObject jsonobj;
				try {
					jsonobj = new JSONObject(jsonStr);
					Success_add = jsonobj.getBoolean("success");
					Message_add = jsonobj.getString("message");

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			if (Success_add == true) {
			
				
				Toast.makeText(getApplicationContext(), Message_add,
						Toast.LENGTH_SHORT).show();
				
				prev(null);
			super.onPostExecute(result);
		}
	}
	}

	
	@Override
	public void onBackPressed() {
		
	}
	
}
